package com.music.service.Impl;

import com.music.service.UserSimilarityCalculator;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;

@Component
public class UserSimilarityCalculatorImpl implements UserSimilarityCalculator {
    @Override
    public double cosineSimilarity(Map<Integer, Integer> userA, Map<Integer, Integer> userB) {
        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;

        for (Integer singleSongId : userA.keySet()) {
            if (userB.containsKey(singleSongId)) {
                dotProduct += userA.get(singleSongId) * userB.get(singleSongId);
            }
            normA += Math.pow(userA.get(singleSongId), 2);
        }

        for (Integer singleSongId : userB.keySet()) {
            normB += Math.pow(userB.get(singleSongId), 2);
        }

        if (normA == 0 || normB == 0) {
            return 0.0; // 避免除以零
        }

        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }
}
